package com.cn.customer.housekeeping.housekeepingb.ui;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.cn.customer.housekeeping.housekeepingb.R;
import com.cn.customer.housekeeping.housekeepingb.bean.BaseResp;
import com.cn.customer.housekeeping.housekeepingb.bean.PayParameterResp;
import com.cn.customer.housekeeping.housekeepingb.bean.ServiceinfoResp;
import com.cn.customer.housekeeping.housekeepingb.biz.personcenter.IUserLoginView;
import com.cn.customer.housekeeping.housekeepingb.biz.personcenter.InterfacePresenter;
import com.cn.customer.housekeeping.housekeepingb.bridge.BridgeFactory;
import com.cn.customer.housekeeping.housekeepingb.bridge.Bridges;
import com.cn.customer.housekeeping.housekeepingb.bridge.cache.sharePref.EBSharedPrefManager;
import com.cn.customer.housekeeping.housekeepingb.bridge.cache.sharePref.EBSharedPrefUser;
import com.cn.customer.housekeeping.housekeepingb.constant.Constants;
import com.cn.customer.housekeeping.housekeepingb.constant.URLUtil;
import com.cn.customer.housekeeping.housekeepingb.ui.base.BaseActivity;
import com.cn.customer.housekeeping.housekeepingb.ui.base.BaseImgView;
import com.cn.customer.housekeeping.housekeepingb.util.NavUtils;
import com.cn.customer.housekeeping.housekeepingb.util.StringUtil;
import com.cn.customer.housekeeping.housekeepingb.util.ToastUtil;
import com.google.gson.Gson;

import static com.cn.customer.housekeeping.housekeepingb.bridge.cache.sharePref.EBSharedPrefUser.username;


/***
 *确认下单
 */
public class MerchandisePlaceOrderActivity extends BaseActivity implements IUserLoginView {
    private InterfacePresenter mInterfacePresenter;
    private EditText et_beizhu, tv_phone, tv_name, tv_menpai;
    private EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
    private RelativeLayout rl_mapchoice;
    private TextView tv_dizhi, tv_goumai, tv_fuwutime, tv_merchandise_name, tv_merchandise_price, iv_shuliang, tv_lianxiren,tv_zongjiage;
    private String serviceid, phone, name;
    private ServiceinfoResp mServiceinfoResp;
    private ImageView img_merchandise, iv_jia, iv_jian;
    private PoiItem mPoiItem;
    private String lat = "";
    private String lon = "";
    private String address = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_merchandiseplaceorder);
        super.onCreate(savedInstanceState);
    }


    @Override
    public void initViews() {
        mInterfacePresenter = new InterfacePresenter();
        mInterfacePresenter.attachView(this);
        et_beizhu = (EditText) findViewById(R.id.et_beizhu);
        tv_goumai = (TextView) findViewById(R.id.tv_goumai);
        rl_mapchoice = (RelativeLayout) findViewById(R.id.rl_mapchoice);
        tv_fuwutime = (TextView) findViewById(R.id.tv_fuwutime);
        img_merchandise = (ImageView) findViewById(R.id.img_merchandise);
        tv_merchandise_name = (TextView) findViewById(R.id.tv_merchandise_name);
        tv_merchandise_price = (TextView) findViewById(R.id.tv_merchandise_price);
        iv_jia = (ImageView) findViewById(R.id.iv_jia);
        iv_jian = (ImageView) findViewById(R.id.iv_jian);
        iv_shuliang = (TextView) findViewById(R.id.iv_shuliang);
        tv_dizhi = (TextView) findViewById(R.id.tv_dizhi);
        tv_name = (EditText) findViewById(R.id.tv_name);
        tv_menpai = (EditText) findViewById(R.id.tv_menpai);
        tv_phone = (EditText) findViewById(R.id.tv_phone);
        tv_lianxiren = (TextView) findViewById(R.id.tv_lianxiren);
        tv_zongjiage = (TextView) findViewById(R.id.tv_zongjiage);
    }

    @Override
    public void initListeners() {
        rl_mapchoice.setOnClickListener(this);
        tv_lianxiren.setOnClickListener(this);
        tv_goumai.setOnClickListener(this);
        iv_jian.setOnClickListener(this);
        iv_jia.setOnClickListener(this);
        et_beizhu.clearFocus();
    }


    @Override
    public void initData() {
        serviceid = getIntent().getExtras().getString(Constants.serviceid);
        address = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.getAoiName, "");
        phone = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.phone, "");
        name = manager.getKDPreferenceUserInfo().getString(username, "");

        tv_name.setText(name);
        tv_phone.setText(phone);
        tv_dizhi.setText(address);

        lat = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lat, "");
        lon = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lon, "");
        mInterfacePresenter.getGetserviceinfo(serviceid);
    }

    @Override
    public void setHeader() {
        super.setHeader();
        rlTitle.setVisibility(View.VISIBLE);
        tvTopTitle.setText("确认下单");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_set://订单跟踪
                NavUtils.gotoMerchandiseTrackActivity(MerchandisePlaceOrderActivity.this);
                break;
            case R.id.rl_mapchoice://地图选择
                NavUtils.gotoMapChoiceActivity(MerchandisePlaceOrderActivity.this, 1000);
                break;
            case R.id.tv_goumai://支付

                if (manager.getKDPreferenceUserInfo().getBoolean(EBSharedPrefUser.isLogin, false)) {
                    ToastUtil.makeText(MerchandisePlaceOrderActivity.this, "请先登录");
                    NavUtils.gotoLoginPasswordActivity(MerchandisePlaceOrderActivity.this);
                } else {
                    PayParameterResp mPayParameterResp = new PayParameterResp();
                    //商品id
                    mPayParameterResp.setServiceid(serviceid);
                    //地址
                    if(StringUtil.isEmpty(tv_dizhi.getText().toString())){
                        ToastUtil.makeText(MerchandisePlaceOrderActivity.this,"请填写地址");
                        return;
                    }
                    mPayParameterResp.setAddress(tv_dizhi.getText().toString());
                    mPayParameterResp.setLat(lat);
                    mPayParameterResp.setLon(lon);
                    //门牌号
                    if(StringUtil.isEmpty(tv_menpai.getText().toString())){
                        ToastUtil.makeText(MerchandisePlaceOrderActivity.this,"请填门牌号");
                        return;
                    }
                    mPayParameterResp.setHoursenum(tv_menpai.getText().toString());
                    //联系人姓名
                    mPayParameterResp.setUsername(tv_name.getText().toString());
                    //联系人电话
                    if(StringUtil.isEmpty(tv_phone.getText().toString())){
                        ToastUtil.makeText(MerchandisePlaceOrderActivity.this,"联系人电话");
                        return;
                    }
                    mPayParameterResp.setPhone(tv_phone.getText().toString());
                    //	服务时间（时间戳）!!!!
                    mPayParameterResp.setBuytimestamp(mServiceinfoResp.getServiceTimestamp());
                    //商品数量
                    mPayParameterResp.setBuycount(iv_shuliang.getText().toString());
                    //  备注
                    mPayParameterResp.setComments(et_beizhu.getText().toString());
                    //  总价
                    mPayParameterResp.setAllprice(tv_zongjiage.getText().toString());

                    NavUtils.gotoPayActivity(MerchandisePlaceOrderActivity.this, mPayParameterResp);
                }


                break;
            case R.id.iv_jia://加好
                int maxNum = Integer.parseInt(mServiceinfoResp.getMaxordercount());
                int dQNum = Integer.parseInt(iv_shuliang.getText().toString());
                if (dQNum > maxNum) {
                    ToastUtil.makeText(MerchandisePlaceOrderActivity.this, "不能大于此数量");
                } else {
                    iv_shuliang.setText((dQNum + 1) + "");
                    int zNum1 = Integer.parseInt(iv_shuliang.getText().toString());
                    int mD1 = Integer.parseInt(  mServiceinfoResp.getPrice());
                    tv_zongjiage.setText((zNum1*mD1)+"");
                }

                break;
            case R.id.iv_jian://减号
                int dQNum2 = Integer.parseInt(iv_shuliang.getText().toString());
                if (dQNum2 > 1) {
                    iv_shuliang.setText((dQNum2 - 1)+"" );
                    int zNum2 = Integer.parseInt(iv_shuliang.getText().toString());
                    int mD2 = Integer.parseInt(  mServiceinfoResp.getPrice());
                    tv_zongjiage.setText((zNum2*mD2)+"");
                } else {
                    ToastUtil.makeText(MerchandisePlaceOrderActivity.this, "不能小于此数量");
                }

                break;
            case R.id.tv_lianxiren://调用联系人
                startActivityForResult(new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI), 1001);
                break;
        }
        super.onClick(v);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {

                case 1000:
                    if (data != null) {
                        mPoiItem = data.getParcelableExtra("PoiItem");
                        lat = mPoiItem.getLatLonPoint().getLatitude() + "";
                        lon = mPoiItem.getLatLonPoint().getLongitude() + "";
                        address = mPoiItem.getTitle();
                        tv_dizhi.setText(address);

                    }
                    break;
                case 1001:
                    String phonename;
                    if (data != null) {
                        // ContentProvider展示数据类似一个单个数据库表
                        // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
                        ContentResolver reContentResolverol = getContentResolver();
                        // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
                        Uri contactData = data.getData();
                        // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
                        Cursor cursor = managedQuery(contactData, null, null, null, null);
                        cursor.moveToFirst();
                        // 获得DATA表中的名字
                        phonename = cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        // 条件为联系人ID
                        String contactId = cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts._ID));
                        // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
                        Cursor phone = reContentResolverol.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                                        + contactId, null, null);

                        while (phone.moveToNext()) {
                            tv_name.setText(phonename);
                            String phonenum = phone
                                    .getString(phone
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            tv_phone.setText(phonenum);
                        }
                        //4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
                        if (Integer.parseInt(Build.VERSION.SDK) < 14) {
                            //只有4.0以下才需要手动关闭
                            phone.close();
                            cursor.close();
                        }
                    }
                    break;
                default:
                    break;
            }
        }

    }

    @Override
    public void onError(BaseResp s) {

    }

    @Override
    public void onSuccess(BaseResp s) {

        if (s.getUrl().equals(URLUtil.url_get_getserviceinfoByid)) {
            Gson gson = new Gson();
            mServiceinfoResp = gson.fromJson(s.getData(), ServiceinfoResp.class);
            //服务时间
            tv_fuwutime.setText(mServiceinfoResp.getServiceTime());
            //商品图片
            BaseImgView.ImageLoaderLoadimg(img_merchandise,
                    mServiceinfoResp.getShopImgurl(), R.mipmap.icon_fang, R.mipmap.icon_fang, R.mipmap.icon_fang, 60, 60, 20);
            //商品名称
            tv_merchandise_name.setText(mServiceinfoResp.getServicename());
            //商品内容
            tv_merchandise_price.setText("维修内容：" + mServiceinfoResp.getServicecontent());
            //总价
            tv_zongjiage.setText(mServiceinfoResp.getPrice()+"");
        }
    }

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
